package util;

import java.sql.*;

public class DBUtil {
    static Connection conn=null;
    static PreparedStatement pps=null;
    static ResultSet resultSet=null;

    public Connection getConn(){
        return getConnection();
    }

    public void close(){
        close(resultSet,conn,pps);
    }

    /**
     * 抽取 获取连接的方法
     * @return
     */
    private static Connection getConnection(){
        try{
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            String userName="root";
            String passWord="64531515z";
            String url="jdbc:mysql://localhost:3306/login?serverTimezone=UTC";
            conn = DriverManager.getConnection(url, userName, passWord);
            return conn;
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        } catch (SQLException throwables){
            throwables.printStackTrace();
        }
        return null;//出现异常，返回null
    }

    private static void close(ResultSet resultSet, Connection conn, PreparedStatement pps)  {
        if (resultSet !=null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pps != null) {
            try {
                pps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
